<?php
namespace App\Services\AppletTemplateMsg;


use App\Facades\EasyWechat;
use App\Models\WxFormidList;
use App\Models\WxTemplatemsgList;
use App\Models\WxTemplatemsgLog;
use App\Services\WxBaseService;

/**
 * 模板消息服务类
 * @package App\Services\WxTemplateMsg
 */
class TemplateMsgService extends \App\Services\WxCommon\WxBase
{
    const TYPE_SERVICE_PROGRESS = 'service_progress';//服务进度通知
    const TYPE_AUDIT_STATUS = 'audit_status';//审核状态通知

    /**
     * 构造函数
     * @param string $appid
     * @throws \Exception
     */
    public function __construct($appid = '')
    {
        parent::__construct($appid);
        $this->app = EasyWechat::miniProgram($this->appid);
    }
    /**
     * 发送服务消息
     * @param string $type 服务消息类型，与常量对应
     * @param array $params ['touser'=>'接收者openid','page'=>'小程序路径', 'data'=>'数组格式，服务消息数据']
     * @return bool
     * @throws \Exception
     */
    public function send($type, $params = [])
    {
        if (empty($params['touser'])){
            throw new \Exception('请指定接收者openid');
        }
        if (empty($params['page'])){
            throw new \Exception('请指定小程序路径');
        }
        if (empty($params['data'])){
            throw new \Exception('请设定服务消息数据');
        }
        $logData = ['appid' => $this->appid, 'key' => $type,'touser'=>$params['touser'], 'page'=> $params['page']];
        \DB::beginTransaction();
        try{
            $findTemplate = WxTemplatemsgList::where('appid', $this->appid)->where('key', $type)->orderBy('id','desc')->first();
            if (empty($findTemplate)){
                throw new \Exception('模板不存在');
            }
            $params['template_id'] = $findTemplate->template_id;
            //获取6天内的formid
            $timeLine = date('Y-m-d H:i:s', strtotime('-6 days'));
            $findFormId = WxFormidList::where('openid', $params['touser'])->where('appid', $this->appid)->where('created_at', '>=', $timeLine)->orderBy('id', 'asc')->first();
            if (empty($findFormId)){
                throw new \Exception('无可用formid');
            }
            $params['form_id'] = $findFormId->form_id;
            $apiRs = $this->app->template_message->send($params);
            $logData['errcode'] = $apiRs['errcode'];
            $logData['errmsg'] = $apiRs['errmsg'];
            //删除formId
            WxFormidList::where('id', $findFormId->id)->delete();

            \DB::commit();
        }catch (\Exception $e){
            \DB::rollBack();
            $logData['errcode'] = $e->getCode() == 0 ? -1 : $e->getCode();
            $logData['errmsg'] = $e->getMessage();
        }
        $logData['data'] = $params;
        WxTemplatemsgLog::create($logData);
        return true;
    }
}